#!/usr/bin/perl -w

use strict;

use Data::Dumper;
use Getopt::Std;
use CIF::Client;
use JSON;

my %opts;
getopt('hSL:p:f:q:c:s:r:', \%opts);

my $query       = $opts{'q'} || shift;
my $debug       = ($opts{'d'}) ? 1 : 0;
my $c           = $opts{'c'} || $ENV{'HOME'}.'/.cif';
my $fields      = $opts{'f'};
my $severity    = $opts{'s'};
my $restriction = $opts{'r'};
my $plugin      = $opts{'p'} || 'table';
my $max_desc    = $opts{'L'} || 100;
my $silent      = $opts{'S'};
my $plugs = join(',',CIF::Client::_plugins);

die(usage()) unless($query || $opts{'h'});


sub usage {
    return <<EOF;
Usage: perl $0 -q xyz.com
    -h  --help:     this message
    -q  --query:    query string (use 'url\\/<md5|sha1>' for url hash lookups)
    -s  --severity: severity (low,medium,high), default: high
    -p  --plugin:   output plugin ($plugs), default: $plugin
    -S  --silent    perform a "silent" query (no log query)

Queries:

    \$> perl $0 -q url\\/f8e74165fb840026fd0fce1fd7d62f5d0e57e7ac
    \$> perl $0 -q hut2.ru
    \$> perl $0 -q hut2.ru,url\\/f8e74165fb840026fd0fce1fd7d62f5d0e57e7ac
    \$> perl $0 hut2.ru

Feeds:
    
    \$> perl $0 -q malware
    \$> perl $0 -q malware -s low
    \$> perl $0 -q infrastructure/network -s medium -p snort
    \$> perl $0 -q domain/malware -p bindzone

    configuration file ~/.cif should be readable and look something like:

    [client]
    host = https://example.com:443/api
    apikey = xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    timeout = 60

EOF
}
my ($client,$err) = CIF::Client->new({ 
    config  => $c,
    fields  => $fields,
    max_desc    => $max_desc,
    silent  => $silent,
});

die($err) unless($client);

my @q = split(/\,/,$query);
foreach (@q){
    $client->GET($_,$severity,$restriction,$silent);
    die('request failed with code: '.$client->responseCode()."\n\n".$client->responseContent()) unless($client->responseCode == 200);
    my $text = $client->responseContent();
   
    if($plugin && lc($plugin) ne 'table'){
        my $plug = 'CIF::Client::Plugin::'.ucfirst($plugin);
        eval "require $plug";
        die($@) if($@);
        my $json = from_json($text);
        print $plug->write_out($client->{'config'},@{$json->{'data'}->{'result'}->{'feed'}->{'items'}}) if($json->{'data'}->{'result'});
    } else {
        print "Query: ".$_;
        $text = $client->table($text) || "\n".'no records'."\n";
        print $text."\n";
    }
}
